package com.googlecode.dgwt.client.dojo.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import com.googlecode.dgwt.client.dojo.exception.FeatureException;


/**
 * @author      Wellington Tadeu dos Santos
 * @since       DGWT v0.01
 */
public class FeatureImpl {

    
    private static final Class<?> OBJECT_CLASS = Object.class;
    
    
    private Map<Class<?>, Object> inheritMap;
    private Set<Class<?>> inheritSet;
    

    public void beginRegister(int count) {
        inheritMap = new HashMap<Class<?>, Object>(count);
    }
    
    public void beginInterfaces() {
        inheritSet = inheritMap.keySet();
    }
    
    public void register(Class<?> classe, Object object) {
        inheritMap.put(classe, object);
    }
    
    public void endRegister() {
    }

    @SuppressWarnings("unchecked")
    public <T extends Object> T inherited(Class<T> classe) {
        
        if (classe != null) {
            Object obj = inheritMap.get(classe);
            
            if (obj != null) {
                return (T) obj;
            }
            
            for (Class<?> classeEntry : inheritSet) {
                if (isSuperclass(classe, classeEntry)) {
                    return (T) inheritMap.get(classeEntry);
                }
            }
        }
        
        throw new FeatureException("No super class found for type \"" + 
                (classe != null ? classe.getName() : null) + "\"");
    }

    
    protected boolean isSuperclass(Class<?> filha, Class<?> pai) {
        do {
            if (pai == filha) {
                return true;
            }
            pai = pai.getSuperclass();
        } while (pai != OBJECT_CLASS);
        return pai == filha;
    }


    public interface FeatureInitializer {
     
        public void ___initialize_feature_impl();
        
    }
    
}
